package com.nicole.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import com.google.code.kaptcha.Producer;
import com.nicole.comm.SysConstants;
import com.nicole.entity.ProperConfig;
import com.nicole.service.impl.SysConfigServiceImpl;
import com.nicole.utils.Base64;
import com.nicole.utils.RedisCache;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class CaptchaController {

    @Resource(name = "captchaProducerText")
    private Producer captchaProducerText;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Resource
    private SysConfigServiceImpl configService;

    @Resource
    private RedisCache redisCache;

    @Value("${nicole.captchaType}")
    private String captchaType;


    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public HashMap<String, Object> getCode(HttpServletResponse servletResponse) {
        HashMap<String, Object> result = new HashMap<>();
        // 检查验证码参数是否开启
        boolean captchaEnable = configService.getCaptchaEnable();
        result.put("captchaEnabled", captchaEnable);
        if (!captchaEnable) {
            return result;
        }
        //保存验证码信息
        String uuid = IdUtil.simpleUUID();
        String captchaKey = SysConstants.CAPTCHA_CODE_KEY + uuid;  //验证码key

        String capStr = null, code = null;
        BufferedImage image = null;
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducerText.createText();
            image = captchaProducerText.createImage(capStr);
        }
        redisCache.setCacheObject(captchaKey,code,SysConstants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

        FastByteArrayOutputStream os = new FastByteArrayOutputStream();

        try {
            ImageIO.write(image,"jpg",os);
        }catch (IOException e){
            log.error("验证码图片生成失败");
        }
        result.put("uuid", uuid);
        result.put("img", Base64.encode(os.toByteArray()));
        return result;
    }
}
